package cn.edu.ujn.finallab.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.edu.ujn.finallab.dao.Customer;
import cn.edu.ujn.finallab.dao.Orders;
import cn.edu.ujn.finallab.dao.Room;
import cn.edu.ujn.finallab.service.IOrderService;
import cn.edu.ujn.finallab.service.IRoomService;

@Controller
public class HandleController {

	@Autowired
	private IOrderService orderService;

	@Autowired
	private IRoomService roomService;

	@RequestMapping("/toHandleIn")
	public String toHandleIn() {
		return "handleIn";
	}

	@RequestMapping("/handleRoomSearch")
	public String roomSearch(HttpServletRequest request, Model model) {
		// 获取参数
		String roomType = request.getParameter("roomType");
		String startTime = request.getParameter("startTime");
		String endTime = request.getParameter("endTime");

		// 将数据价格转换成int型返回到前端
		String low = request.getParameter("lowPrice");
		String high = request.getParameter("highPrice");
		Integer lowPrice = null;
		Integer highPrice = null;
		if (!low.equals("") && !high.equals("")) {
			Double lowDPrice = Double.parseDouble(low);
			Double highDPrice = Double.parseDouble(high);
			lowPrice = lowDPrice.intValue();
			highPrice = highDPrice.intValue();
		}
		// 将传过来的参数插入Map里，传到数据库
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("pType", roomType);
		map.put("pLowPrice", lowPrice);
		map.put("pHighPrice", highPrice);

		List<Room> result = new ArrayList<Room>();
		result.addAll(roomService.findUnreservedRoomByTypeAndPriceRoom(map));

		List<Room> reservedRoomLists = roomService.findReservedRoomByTypeAndPrice(map);
		// 遍历找到的每个房间
		for (Room r : reservedRoomLists) {
			// 得到该房间的所有订单，判断是否符合输入时间段的条件
			List<Orders> ordersList = r.getOrderLists();
			// 将订单表按入住时间从小到大排序
			Collections.sort(ordersList, new Comparator<Orders>() {
				@Override
				public int compare(Orders o1, Orders o2) {
					return o1.getInTime().compareTo(o2.getInTime());
				}
			});

			int n = ordersList.size();
			for (int i = 0; i < n; i++) {// 如果输入的开始时间大于上一个订单的结束时间，输入的结束时间大于下一个订单干的开始时间，则该房间能预定
				if (i < n - 1) {
					Orders o1 = ordersList.get(i);
					Orders o2 = ordersList.get(i + 1);
					if (startTime.compareTo(o1.getOutTime()) > 0 && endTime.compareTo(o2.getInTime()) < 0) {
						result.add(r);
						break;
					}
				} else {// 如果找到了最后一个订单，则只用判断输入的开始时间是否大于最后一个订单的结束时间。大于该房则可预订
					Orders o1 = ordersList.get(i);
					if (startTime.compareTo(o1.getOutTime()) > 0) {
						result.add(r);
						break;
					}
				}

			}
		}

		// 如果未查到任何房间，则返回错误信息
		if (result.isEmpty())
			model.addAttribute("msg", "未查询到符合条件的房间");
		model.addAttribute("roomList", result);
		model.addAttribute("roomType", roomType);
		model.addAttribute("startTime", startTime);
		model.addAttribute("endTime", endTime);
		model.addAttribute("lowPrice", lowPrice);
		model.addAttribute("highPrice", highPrice);
		return "handleIn";
	}

	@RequestMapping("/handle")
	public String handle(String startTime, String endTime, String number, HttpSession session) {
		// 算出总共入住天数
		SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");// 年月日
		Date inDate = null;
		Date outDate = null;
		try {
			inDate = sdf1.parse(startTime);
			outDate = sdf1.parse(endTime);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Calendar c1 = Calendar.getInstance();
		c1.setTime(inDate);
		Calendar c2 = Calendar.getInstance();
		c2.setTime(outDate);
		int days = c2.get(Calendar.DAY_OF_YEAR) - c1.get(Calendar.DAY_OF_YEAR);

		// 生成订单号
		SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
		String date = df.format(new Date());
		// 根据房号找到房间
		Room room = this.roomService.selectByNumber(number);
		// 生成订单
		Orders order = new Orders();
		order.setOrderNumber(date);
		order.setInTime(startTime);
		order.setOutTime(endTime);
		order.setRoomNumber(number);
		order.setPrice(room.getPrice() * days);
		order.setState("1");
		session.setAttribute("order", order);
		session.setAttribute("type", room.getType());
		session.setAttribute("room", room);
		return "inputCustomer";
	}
	@RequestMapping("/customerInput")
	public String customerInput(String name,String phone,String idcard,HttpSession session) {
		Orders order = (Orders) session.getAttribute("order");
		order.setCustomerName(name);
		order.setCustomerPhone(phone);
		order.setCustomerIdcard(idcard);
		session.setAttribute("order", order);
		return "handleShowOrder";
	}
	// 用户点击确定后，将订单插入数据库
		@Transactional
		@RequestMapping("/handleOrderConfirm")
		public String orderConfirm(HttpSession session, Model model) {
			//将房间状态改为已预定
			Room room = (Room) session.getAttribute("room");
			room.setState("已入住");		
			int updateRoom = roomService.updateRoom(room);
			
			//从session中获取页面传过来的订单对象，将其插入
			Orders order = (Orders) session.getAttribute("order");
			
			int insert = this.orderService.insertOrder(order);		
			if (insert > 0&&updateRoom>0)
				model.addAttribute("msg", "订单创建成功");
			else
				model.addAttribute("msg", "订单创建失败，请重新选择");
			
			session.removeAttribute("room");
			session.removeAttribute("order");		
			return "handleIn";
		}
}
